package com.hxexp.weixin.mvc.userinfo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

import com.hxexp.weixin.common.exception.APIException;
import com.hxexp.weixin.common.exception.ServiceException;
import com.hxexp.weixin.constant.CacheName;
import com.hxexp.weixin.constant.Errcode;
import com.hxexp.weixin.hpe.api.userupdate.UserUpdateAPI;
import com.hxexp.weixin.hpe.api.userupdate.model.UserUpdateParamBean;
import com.hxexp.weixin.hpe.api.userupdate.model.UserUpdateResultBean;
import com.hxexp.weixin.mvc.userinfo.service.UserInfoService;

/**
 * 用户信息服务实现类
 *
 * @author li.jiang
 *
 */
@Service
public final class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserUpdateAPI userUpdateAPI;
    @Autowired
    private EhCacheCacheManager ehCacheManager;
    /* (non-Javadoc)
     * @see com.hxexp.weixin.mvc.userinfo.service.UserInfoService#updateUserInfo(com.hxexp.weixin.hpe.api.userupdate.model.UserUpdateParamBean)
     */
    @Override
    public UserUpdateResultBean updateUserInfo(UserUpdateParamBean userUpdateParam) throws ServiceException {

        UserUpdateResultBean userUpdateResult = new UserUpdateResultBean();

        // 检查验证码是否失效
        Cache captchaCache = ehCacheManager.getCache(CacheName.HPE_ACCOUNTINFO_CAPTCHA);
        String captchaFromCache = captchaCache.get(userUpdateParam.getUserId(), String.class);

        // 验证码未失效
        if (captchaFromCache != null) {
            // 输入的验证码和缓存中的验证码一致,
            if (captchaFromCache.equals(userUpdateParam.getCaptcha())) {
                // do nothing
            } else {
                // 输入的验证码和缓存中的验证码不一致
                userUpdateResult.setErrcode(Errcode.CAPTCHA_ERROR);
                userUpdateResult.setErrmsg(Errcode.getMessage(Errcode.CAPTCHA_ERROR));
                return userUpdateResult;
            }
        } else {
            // 验证码已失效
            userUpdateResult.setErrcode(Errcode.CAPTCHA_INVALID);
            userUpdateResult.setErrmsg(Errcode.getMessage(Errcode.CAPTCHA_INVALID));
            return userUpdateResult;
        }

        try {
            userUpdateResult = userUpdateAPI.userUpdate(userUpdateParam);
        } catch (APIException e) {
            throw new ServiceException(e);
        }

        return userUpdateResult;
    }

}
